﻿using System;
using NLog;
using TeamCityConfigurationMonitor.Core;
using System.ServiceProcess;
using System.Linq;
using System.Threading;

namespace TeamCityConfigurationMonitor
{
    class Program : ServiceBase
	{
	    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
        private ConfigurationMonitor monitor;

		static void Main(string[] args)
		{
		    if ("/service".Equals(args.FirstOrDefault()))
		        RunService();
		    else
		        RunConsole(args);
		}

        private static void RunService()
        {
            Logger.Info("Starting in service mode");

            Run(new Program());
        }

        static void RunConsole(string[] args)
        {
            Logger.Info("Starting in console mode");

            var s = new Program();

            s.OnStart(args);

            Console.Read();

            s.OnStop();
        }

        protected override void OnStart(string[] args)
        {
            ThreadPool.QueueUserWorkItem(ignored => Run());
        }

        private void Run()
        {
            try
            {
                monitor = new ConfigurationMonitor(new FileConfiguration());
                monitor.Start();
            }
            catch (Exception e)
            {
                Logger.FatalException("Exiting", e);
                throw;
            }
        }

        protected override void OnStop()
        {
            monitor.Dispose();
        }
	}
}
